package com.xb.loan.cashier.biz.job;

import com.xb.loan.cashier.biz.dao.bean.CashierPayChannel;
import com.xb.loan.cashier.biz.pay.alipay.AlipayPayment;
import com.xb.loan.cashier.biz.service.CashierEncashOrderService;
import com.xb.loan.cashier.service.constant.ICashierEnumConst;
import com.xb.loan.util.qrtz.task.AbstractSimpleTask;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * 支付宝退票文件处理任务
 * 请参考：AlipayRefundEncashThread
 */
public class ThirdAccountEncashRefundAlipayChannelJob extends AbstractSimpleTask {

    private static final Logger logger = LoggerFactory.getLogger(ThirdAccountEncashRefundAlipayChannelJob.class);
    
    public ThirdAccountEncashRefundAlipayChannelJob(){
    }
    
    private CashierPayChannel cashierPayChannel;
    private String day;
    private String fileName;
    private String filePath;
    private String signType;
    
    CashierEncashOrderService cashierEncashOrderService;
    
    @Override
    public void run(){
        // 初始化参数
    	logger.info("支付宝退票文件处理任务ThirdAccountEncashRefundAlipayChannelJob初始化参数验证开始");
        initParams();
        logger.info("支付宝退票文件处理任务ThirdAccountEncashRefundAlipayChannelJob初始化参数验证结束");
        
        cashierEncashOrderService = getSpringBean("cashierEncashOrderService");
        
        String payChannelId = cashierPayChannel.getPayChannelId();
        String partner = cashierPayChannel.getChannelUser();
        String signKey = ICashierEnumConst.CashierEncryptType.MD5.getDesc().equals(signType)?cashierPayChannel.getMd5Key():cashierPayChannel.getPrivateKey();
        String payUrl = cashierPayChannel.getPayUrl();
        Boolean isSuccess = false;
        try {
            isSuccess = AlipayPayment.bptb_refund_file(day, fileName, filePath, partner, signType, signKey, payUrl);
        } catch (IOException e) {
            logger.warn("day="+day+" fileName="+fileName+" payChannelId="+payChannelId+"  msg=下载文件失败");
            throw new RuntimeException("day="+day+" fileName="+fileName+" payChannelId="+payChannelId+"  msg=下载文件失败");
        }
        // 下载失败
        if(!isSuccess){
            logger.warn("day="+day+" fileName="+fileName+" payChannelId="+payChannelId+"  msg=下载退票文件失败");
            return ;
        }
        BufferedReader reader = null;
        String line = null;
        fileName = filePath + "/" + fileName;//文件路径
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "GBK"));
            int row = 0;
            while(true){
            	line = reader.readLine();
                if(++row<4){
                    continue;
                }
                if(StringUtils.isBlank(line)){
                	logger.info("文件："+fileName + " 第" + row + "行 没有要处理行数据");
                    break;
                }
                logger.info("文件："+fileName+" 要处理行数据," + row + " ---> " + line);
                String[] values = line.split(",");
                String orderId = values[1];//  流水号
                logger.info("退单ID为：" + orderId);
                // 处理失败需要抛出异常，让任务重新执行
                cashierEncashOrderService.refundEncashResult(orderId, day);
            }
        }catch (Exception e) {
            logger.error("day="+day+" fileName="+fileName+" payChannelId="+payChannelId+"  msg=处理异常", e);
            throw new RuntimeException("day="+day+" fileName="+fileName+" payChannelId="+payChannelId+"  msg=处理异常");
        }finally{
            if(reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                }
                reader = null;
            }
        }
    }
    
    private void initParams() {
        Map<String, Object> params = getParams();
        if(params==null){// 这个任务的参数必须不能为空，初始化的时候就传递了
            logger.warn("参数params为空");
            throw new RuntimeException("参数params为空");
        }
        if((cashierPayChannel=(CashierPayChannel) params.get("cashierPayChannel"))==null){
            logger.warn("cashierPayChannel参数为空");
            throw new RuntimeException("cashierPayChannel参数为空");
        }
        if((day=(String) params.get("date"))==null){
            logger.warn("date参数为空");
            throw new RuntimeException("date参数为空");
        }
        if((fileName=(String) params.get("fileName"))==null){
            logger.warn("fileName参数为空");
            throw new RuntimeException("fileName参数为空");
        }
        if((filePath=(String) params.get("filePath"))==null){
            logger.warn("filePath参数为空");
            throw new RuntimeException("filePath参数为空");
        }
        if((signType=(String) params.get("signType"))==null){
            logger.warn("signType参数为空");
            throw new RuntimeException("signType参数为空");
        }
    }

    public void setCashierPayChannel(CashierPayChannel cashierPayChannel) {
        this.cashierPayChannel = cashierPayChannel;
    }

    public void setDate(String date) {
        this.day = date;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public void setSignType(String signType) {
        this.signType = signType;
    }
    
}
